from setting import Setting
import data
import os
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras import backend
from keras import layers
from keras import models
from keras.models import load_model

def sample(preds, temperature=1.0):
  """
  从给定的preds中随机选择5个下标。
  当temperature固定时，preds中的值越大，选择其下标的概率就越大；
  当temperature不固定时，
      temperature越大，选择值小的下标的概率相对提高，
      temperature越小，选择值大的下标的概率相对提高。
  :param preds: 概率分布序列，其和为1.0
  :param temperature: 当temperature==1.0时，相当于直接对preds进行轮盘赌法
  :return:
  """
  preds = np.asarray(preds).astype(np.float64)
  # preds1 = np.log(preds) / temperature
  exp_preds = np.exp(preds)
  preds2 = exp_preds / np.sum(exp_preds)
  # probas = np.random.multinomial(1, preds2, 1)
  # re = np.argmax(probas)
  # probas = np.random.multinomial(1, preds2, 1)
  # re = np.argmax(probas)
  re = np.argmax(preds2)
  return re

def updateData(predicts_, predict_y):
  """ 统计所有结果里面，间隔多少个结果不对的情况 """
  data = []
  correct = 0
  total =  len(predicts_)
  for i in range(total):
    balls= sample(predicts_[i])
    if predict_y[i] != balls:
      correct = correct + 1
    else:
      data.append(correct)
      correct = 0
  print(data)
  updateMoney(data, [1])
  updateMoney(data, [1, 3, 7])
  updateMoney(data, [1, 3, 7, 24, 70])
  updateMoney(data, [1, 3, 7, 24, 70, 200])
  return data

def updateMoney(data, moneyTpye=[1, 3, 7]):
  money = 0
  cur = 0
  min = 0
  max = 0
  for i in range(len(data)):
    if data[i] == 0:
      money = money +(moneyTpye[cur] * 0.96)
      cur = 0
    else:
      for j in range(data[i]):
        money = money - moneyTpye[cur]
        cur = (cur + 1) % len(moneyTpye)
    if money > max:
      max = money
    if money < min:
      min = money
  print(money, min, max)

def getFiles(path):
  files = os.listdir(path)
  return files

def predict_(set, i0, i1, i2, i3, i4, i5, i6):
  # 获取数据
  train_x, train_y, test_x, test_y, predict_x, predict_y = data.getDate(set, False)
  # 获取文件夹地址
  path = os.path.split(os.path.realpath(__file__))[0]
  # 加载整个模型
  model = load_model('{}/{}/{}_{}_{}_{}_{}_{}_{}.h5'.format(path,set.CHECKPOINTS_PATH,i0,i1, i2, i3, i4, i5, i6))
  # 开始预测
  predicts = model.predict(predict_x, batch_size=1)
  correct = 0
  total =  len(predicts)
  for i in range(total):
    balls= sample(predicts[i])
    if predict_y[i] == balls:
      correct = correct + 1
  print("# {}_{}_{}_{}_{}_{}_{}   正确的个数为：{} / {}  - {}%".format(i0, i1, i2, i3, i4, i5, i6,correct,total, round(correct/total*100,2)))
  # 除之前的模型.
  backend.clear_session()
  return updateData(predicts, predict_y)

if __name__ == '__main__':
  set = Setting()
  # 获取文件夹地址
  path = os.path.split(os.path.realpath(__file__))[0]
  getFilesList = getFiles(path + "/" + set.CHECKPOINTS_PATH)
  for item in range(0, len(getFilesList)):
    item = getFilesList[item]
    if item.split(".")[-1:][0] == "png":
      continue
    item = item[:-3]
    sl = item.split("_")
    s = []
    for _ in sl:
      if _: s.append(_)
    sl = s
    sl[0] = sl[0] + "_"
    for i in range(1, len(sl)):
      if i == 4:
        sl[i] = float(sl[i])
        continue
      if i == 6:
        sl[i] = float(sl[i])
        continue
      sl[i] = int(sl[i])
    set.setDef(EPOCHS_=sl[1], BATCH_SIZE_=sl[2], MAX_STEPS_=sl[3], DROPOUT_RATE_=sl[4], LSTM_UNITS_=sl[5])
    # predict_(set,sl[0],sl[1],sl[2],sl[3],sl[4],sl[5],sl[6])
    # 测试b开头的文件
    if sl[0][0:1] == "c":
      predict_(set,sl[0],sl[1],sl[2],sl[3],sl[4],sl[5],sl[6])

  # sl = ["b0005", 30, 25, 30, 0.6, 32]
  # set.setDef(EPOCHS_=sl[1], BATCH_SIZE_=sl[2], MAX_STEPS_=sl[3], DROPOUT_RATE_=sl[4], LSTM_UNITS_=sl[5])
  # predict_(set,sl[0],sl[1],sl[2],sl[3],sl[4],sl[5],)
